package dry.example.gui;

import javax.swing.*;
import javax.swing.border.Border;
import java.awt.*;

public class GridBagLayoutWithBordersDemo {
    public static void main(String[] args) {
        // 创建主窗口
        JFrame frame = new JFrame("GridBagLayout 带边框示例");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(600, 400);

        // 设置面板为 GridBagLayout
        JPanel panel = new JPanel(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();

        // 定义边框样式
        Border blackLine = BorderFactory.createLineBorder(Color.BLACK);

        // 标签和文本框 - 姓名
        JLabel nameLabel = new JLabel("姓名:");
        JTextField nameField = new JTextField(20); // 文本框宽度设为20个字符宽

        // 添加边框
        nameLabel.setBorder(blackLine);
        nameField.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createLineBorder(Color.BLUE),
                BorderFactory.createEmptyBorder(5, 5, 5, 5))); // 内边距

        // 配置 GridBagConstraints 并添加组件
        gbc.gridx = 0;
        gbc.gridy = 0;
        gbc.anchor = GridBagConstraints.LINE_END; // 右对齐
        gbc.insets = new Insets(5, 5, 5, 5); // 外边距
        panel.add(nameLabel, gbc);

        gbc.gridx = 1;
        gbc.gridy = 0;
        gbc.anchor = GridBagConstraints.LINE_START; // 左对齐
        panel.add(nameField, gbc);

        // 标签和文本框 - 年龄
        JLabel ageLabel = new JLabel("年龄:");
        JTextField ageField = new JTextField(3); // 文本框宽度设为3个字符宽

        // 添加边框
        ageLabel.setBorder(blackLine);
        ageField.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createLineBorder(Color.GREEN),
                BorderFactory.createEmptyBorder(5, 5, 5, 5)));

        gbc.gridx = 0;
        gbc.gridy = 1;
        panel.add(ageLabel, gbc);

        gbc.gridx = 1;
        gbc.gridy = 1;
        panel.add(ageField, gbc);

        // 按钮 - 提交
        JButton submitButton = new JButton("提交");

        // 添加边框
        submitButton.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createLineBorder(Color.RED),
                BorderFactory.createEmptyBorder(5, 15, 5, 15))); // 更大的内边距

        gbc.gridx = 1;
        gbc.gridy = 2;
        gbc.gridwidth = 2; // 跨越两列
        gbc.anchor = GridBagConstraints.CENTER; // 居中对齐
        gbc.fill = GridBagConstraints.HORIZONTAL; // 水平填充
        gbc.weightx = 1.0; // x方向权重设为1.0，使得按钮能随窗口拉伸
        panel.add(submitButton, gbc);

        // 将面板加入窗口
        frame.add(panel, BorderLayout.CENTER);

        // 显示窗口
        frame.setVisible(true);
    }
}
